﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using CCWin.SkinControl;
using DSAClient.Models.Input;
using DSAClient.Properties;

namespace DSAClient
{
    public partial class ImageForm : TemplateForm
    {
        private int mouseLocationX = 0;          //初始化鼠标当前X坐标
        private int mouseLocationY = 0;          //初始化鼠标当前Y坐标

        public string imgSize = "";
        public string picturetype = "普通照片";
        private List<bool> canMoveList;
        internal int totalnum = 0;
        internal int surplusnum = 0;
        internal int tempNum = 0;
        internal bool isTxtChange = true;

        internal XControls.OpaqueLayerControl p = null;


        public ImageForm()
        {
            InitializeComponent();
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);//禁止擦除背景.
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//双缓冲
            this.UpdateStyles();
            this.panel10.Width = this.lbName.Width + 10;
            panel18.BackColor = Color.FromArgb(65, 204, 212, 230);
            if (sizeImageInfo.iserror)
            {
                llbLog.Visible = true;
            }
            else
            {
                llbLog.Visible = false;
            }
            //CreateCutRectangle();

        }

        public ImageForm(int allnum, int num, string size, string pictype, string name)
        {
            InitializeComponent();

            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);//禁止擦除背景.
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//双缓冲
            this.UpdateStyles();
            imgSize = size;
            picturetype = pictype;
            lbSize.Text = size;
            lbNum.Text = num.ToString() + "张";
            lbName.Text = name.Length > 20 ? name.Substring(0, 20) + "..." : name;
            this.panel10.Width = this.lbName.Width + 10;
            totalnum = allnum;
            surplusnum = num;
            ReplaceMessage();
            panel18.BackColor = Color.FromArgb(65, 204, 212, 230);
            //CreateCutRectangle();
            if (sizeImageInfo.iserror)
            {
                llbLog.Visible = true;
            }
            else
            {
                llbLog.Visible = false;
            }
        }

        internal void ReplaceMessage()
        {
            lbtotalnum.Text = sizeImageInfo.totalnum.ToString(); //totalnum.ToString();
            lbsurplusnum.Text = sizeImageInfo.surplusnum.ToString(); //surplusnum.ToString();
        }

        #region 注释
        ///// <summary>
        ///// 创建8个矩形裁剪框
        ///// </summary>
        //public void CreateCutRectangle()
        //{
        //    if (rectList == null)
        //    {
        //        rectList = new List<Rectangle>();
        //        canMoveList = new List<bool>();

        //        for (int i = 0; i < 8; i++)
        //        {
        //            bool canmove = false;
        //            canMoveList.Add(canmove);
        //            Rectangle m_Rect = new Rectangle(0, 0, 0, 0);           //初始化矩形裁剪选框
        //            m_Rect.Width = (int)(299 * 0.8f);
        //            m_Rect.Height = (int)(201 * 0.8f);

        //            //居中显示
        //            m_Rect.X = (299 - m_Rect.Width) / 2;
        //            m_Rect.Y = (201 - m_Rect.Height) / 2;
        //            rectList.Add(m_Rect);
        //        }
        //    }
        //}
        #endregion

        /// <summary>
        /// 显示图片
        /// </summary>
        /// <param name="imageList">图片列表对象</param>
        /// <param name="currpage">当前图片显示到哪一页</param>
        public void ShowImage(int currpage)
        {
            pictureBox1.Image = null;
            pictureBox5.Image = null;
            pictureBox2.Image = null;
            pictureBox6.Image = null;
            pictureBox3.Image = null;
            pictureBox7.Image = null;
            pictureBox4.Image = null;
            pictureBox8.Image = null;

            txtNum1.Text = "1";
            txtNum2.Text = "1";
            txtNum3.Text = "1";
            txtNum4.Text = "1";
            txtNum5.Text = "1";
            txtNum6.Text = "1";
            txtNum7.Text = "1";
            txtNum8.Text = "1";

            int imagecount = imageInfoList.Count;
            int imagepage = Int32.Parse(Math.Ceiling((double)imagecount / 8).ToString());
            try
            {
                if (currpage < imagepage)
                {
                    int begin = (currpage - 1) * 8;
                    for (int i = 1; i < 9; i++)
                    {
                        Control control = Controls.Find("pictureBox" + i, true)[0];

                        PictureBox pb = (PictureBox)control;
                        //pb.Size = ParsePictureBoxSize(imageInfoList[begin + i - 1].Img, 299, 201);
                        Control panelcontrol = Controls.Find("panel" + (i).ToString(), true)[0];
                        Image img = Image.FromFile(imageInfoList[begin + i - 1].ImgPath);
                        AdjustmentImgRotation(img, psi.height, psi.width, imageInfoList[begin + i - 1]);
                        ParsePictureBoxSize(img, pb, 299, 201, panelcontrol.Size);
                        //ParsePictureBoxSize(imageInfoList[begin + i - 1].Img, pb, 299, 201, panelcontrol.Size);
                        //pb.Size = imageInfoList[begin + i - 1].PicSize;
                        pb.Image = img;

                        //旋转图片
                        for (int j = 0; j < imageInfoList[begin + i - 1].RotateNum; j++)
                        {
                            pb.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        }
                        pb.Refresh();
                        control = Controls.Find("txtNum" + i, true)[0];
                        TextBox txt = (TextBox)control;
                        txt.Text = imageInfoList[begin + i - 1].ImgNum.ToString();
                    }
                }
                else
                {
                    int begin = (currpage - 1) * 8;
                    for (int i = 1; i < imagecount - (currpage - 1) * 8 + 1; i++)
                    {
                        Control control = Controls.Find("pictureBox" + i, true)[0];
                        PictureBox pb = (PictureBox)control;
                        //pb.Size = ParsePictureBoxSize(imageInfoList[begin + i - 1].Img, 299, 201);
                        Control panelcontrol = Controls.Find("panel" + (i).ToString(), true)[0];
                        Image img = Image.FromFile(imageInfoList[begin + i - 1].ImgPath);
                        AdjustmentImgRotation(img, psi.height, psi.width, imageInfoList[begin + i - 1]);
                        ParsePictureBoxSize(img, pb, 299, 201, panelcontrol.Size);
                        //pb.Size = imageInfoList[begin + i - 1].PicSize;
                        pb.Image = img;
                        //旋转图片
                        for (int j = 0; j < imageInfoList[begin + i - 1].RotateNum; j++)
                        {
                            pb.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        }
                        pb.Refresh();
                        control = Controls.Find("txtNum" + i, true)[0];
                        TextBox txt = (TextBox)control;
                        txt.Text = imageInfoList[begin + i - 1].ImgNum.ToString();
                    }
                }
            }
            catch { }
            ReplaceMessage();
            isTxtChange = true;
            GC.Collect();
        }

        //private Size ParsePictureBoxSize(Image img, int width, int height)
        //{
        //    Size size = new Size();
        //    if ((float)img.Width / (float)img.Height < (float)width / (float)height)
        //    {
        //        size.Height = height;
        //        size.Width = img.Width * height / img.Height;
        //    }
        //    else
        //    {
        //        size.Width = width;
        //        size.Height = img.Height * width / img.Width;
        //    }
        //    return size;
        //}

        /// <summary>
        /// 旋转图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RotationImage_Click(object sender, EventArgs e)
        {
            try
            {
                string strIndex = ((SkinButton)sender).Name.Replace("sbtnRotationImage", "");
                int imgIndex = (currpage - 1) * 8 + Int32.Parse(strIndex) - 1;

                Control control = Controls.Find("pictureBox" + strIndex, true)[0];
                PictureBox pb = (PictureBox)control;

                //Image img = pb.Image;
                pb.Image.RotateFlip(RotateFlipType.Rotate270FlipNone);
                pb.Refresh();
                //pb.Image = img;

                if (imageInfoList[imgIndex] != null && imageInfoList[imgIndex].ImgPath != "")
                {
                    imageInfoList[imgIndex].RotateNum = (imageInfoList[imgIndex].RotateNum + 1) % 4;
                }
            }
            catch
            { }
        }

        private void Cancel_Click(object sender, EventArgs e)
        {

        }

        //private void DisplalyRect(int index)
        //{

        //    Control control = Controls.Find("pictureBox" + index.ToString(), true)[0];
        //    PictureBox pb = (PictureBox)control;
        //    Graphics g = pb.CreateGraphics();
        //    if (rectList[index] != null)
        //    {
        //        g.DrawRectangle(new Pen(new SolidBrush(Color.Red), 1), rectList[index]);
        //    }
        //    pb.Invalidate();
        //}

        private void pictureBox_Paint(object sender, PaintEventArgs e)
        {
            if (((PictureBox)sender).Image != null)
            {
                if (imageInfoList.Count > 0)
                {
                    int strIndex = Int32.Parse(((PictureBox)sender).Name.Replace("pictureBox", "")) - 1;
                    int imgIndex = (currpage - 1) * 8 + strIndex;

                    Control control = Controls.Find("sbtnOpenpic" + (strIndex + 1).ToString(), true)[0];
                    SkinButton sbtn = (SkinButton)control;
                    if (imageInfoList[imgIndex] != null && imageInfoList[imgIndex].ImgPath != "")
                    {
                        if (imageInfoList[imgIndex].IsOpenPic)
                            sbtn.Visible = true;
                        else
                            sbtn.Visible = false;

                        if (imageInfoList[imgIndex].IsCut)
                        {
                            Graphics g = e.Graphics;
                            //if (imageInfoList[imgIndex].Rect != null)
                            //{
                            //    imageInfoList[imgIndex].RectPoint = new Point(imageInfoList[imgIndex].Rect.X, imageInfoList[imgIndex].Rect.Y);
                            //    g.DrawRectangle(new Pen(new SolidBrush(Color.Red), 1), imageInfoList[imgIndex].Rect);
                            //}
                            if (imageInfoList[imgIndex].IsCut)
                            {
                                imageInfoList[imgIndex].RectPoint = new Point(imageInfoList[imgIndex].Rect.X, imageInfoList[imgIndex].Rect.Y);
                                g.DrawRectangle(new Pen(new SolidBrush(Color.Red), 1), imageInfoList[imgIndex].Rect);
                            }
                        }
                    }
                    else
                    {
                        sbtn.Visible = true;
                    }
                }
                else
                {
                    ((PictureBox)sender).Image = null;
                }
            }
            else
            {
                if (imageInfoList.Count > 0)
                {
                    try
                    {
                        int strIndex = Int32.Parse(((PictureBox)sender).Name.Replace("pictureBox", "")) - 1;
                        int imgIndex = (currpage - 1) * 8 + strIndex;

                        Control control = Controls.Find("sbtnOpenpic" + (strIndex + 1).ToString(), true)[0];
                        SkinButton sbtn = (SkinButton)control;
                        if (imageInfoList[imgIndex] != null && imageInfoList[imgIndex].ImgPath != "")
                        {
                            if (imageInfoList[imgIndex].IsOpenPic)
                                sbtn.Visible = true;
                            else
                                sbtn.Visible = false;
                        }
                        else
                            sbtn.Visible = true;
                    }
                    catch { }
                }
            }
        }

        //pictureBox内鼠标单击事件响应，保证鼠标在矩形选框内才可响应鼠标移动事件
        private void pictureBox_MouseDown(object sender, MouseEventArgs e)
        {
            if (((PictureBox)sender).Image != null)
            {
                int index = Int32.Parse(((PictureBox)sender).Name.Replace("pictureBox", "")) - 1;
                int imgIndex = (currpage - 1) * 8 + index;

                Rectangle m_Rect = imageInfoList[imgIndex].Rect;
                Control control = Controls.Find("pictureBox" + (index + 1).ToString(), true)[0];
                PictureBox pb = (PictureBox)control;

                Point pt = pb.PointToClient(Control.MousePosition);
                if (pt.X < m_Rect.X || pt.X > m_Rect.X + m_Rect.Width || pt.Y < m_Rect.Y || pt.Y > m_Rect.Y + m_Rect.Height)
                    imageInfoList[imgIndex].CanMove = false;
                else
                {
                    imageInfoList[imgIndex].CanMove = true;
                    mouseLocationX = pt.X;    //更新当前鼠标X坐标
                    mouseLocationY = pt.Y;    //更新当前鼠标Y坐标
                }
            }
        }

        //鼠标矩形选框内移动事件响应，保证矩形选框始终在pictureBox控件内部
        private void pictureBox_MouseMove(object sender, MouseEventArgs e)
        {
            if (((PictureBox)sender).Image != null)
            {
                int index = Int32.Parse(((PictureBox)sender).Name.Replace("pictureBox", "")) - 1;
                int imgIndex = (currpage - 1) * 8 + index;

                Control control = Controls.Find("pictureBox" + (index + 1).ToString(), true)[0];
                PictureBox pb = (PictureBox)control;
                if (imageInfoList[imgIndex].CanMove)
                {
                    Rectangle m_Rect = imageInfoList[imgIndex].Rect;
                    Point pt = pb.PointToClient(Control.MousePosition);    //获取鼠标相对pictureBox控件的坐标
                    m_Rect.X += pt.X - mouseLocationX;
                    m_Rect.Y += pt.Y - mouseLocationY;
                    mouseLocationX = pt.X;
                    mouseLocationY = pt.Y;

                    m_Rect.X = m_Rect.X < 0 ? 0 : m_Rect.X;
                    m_Rect.Y = m_Rect.Y < 0 ? 0 : m_Rect.Y;
                    m_Rect.X = m_Rect.X + m_Rect.Width > pb.Width ? pb.Width - m_Rect.Width : m_Rect.X;
                    m_Rect.Y = m_Rect.Y + m_Rect.Height > pb.Height ? pb.Height - m_Rect.Height : m_Rect.Y;

                    imageInfoList[imgIndex].Rect = m_Rect;

                    pb.Invalidate();     //重绘pictureBox控件
                }
            }
        }

        //鼠标按键弹起事件响应，保证鼠标没有按键按下时无法响应鼠标移动事件
        private void pictureBox_MouseUp(object sender, MouseEventArgs e)
        {
            if (((PictureBox)sender).Image != null)
            {
                int index = Int32.Parse(((PictureBox)sender).Name.Replace("pictureBox", "")) - 1;
                int imgIndex = (currpage - 1) * 8 + index;
                imageInfoList[imgIndex].CanMove = false;
            }
        }

        private void pictureBox_DoubleClick(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)sender;
            if (pb.Image != null)
            {
                int index = Int32.Parse(((PictureBox)sender).Name.Replace("pictureBox", "")) - 1;
                int imgIndex = (currpage - 1) * 8 + index;

                Rectangle rect = imageInfoList[imgIndex].Rect;
                Image img = ((PictureBox)sender).Image;
                AllMapForm form = (AllMapForm)OpenForm("AllMapForm", new object[] { img, psi.height, psi.width, imageInfoList[imgIndex] });
                if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    rect.Location = form.point;
                    imageInfoList[imgIndex].Rect = rect;
                    pb.Invalidate();
                }
            }
        }

        private void sbtnReduction_Click(object sender, EventArgs e)
        {
            int index = Int32.Parse(((SkinButton)sender).Name.Replace("sbtnReduction", ""));
            Control control = Controls.Find("pictureBox" + (index).ToString(), true)[0];
            PictureBox pb = (PictureBox)control;
            if (pb.Image != null)
            {
                int imgIndex = (currpage - 1) * 8 + index - 1;
                control = Controls.Find("txtNum" + index.ToString(), true)[0];
                TextBox txt = (TextBox)control;
                if (txt.Text == "")
                    txt.Text = "1";
                tempNum = Convert.ToInt32(txt.Text);
                if (int.Parse(txt.Text) > 1)
                {
                    txt.Text = (int.Parse(txt.Text) - 1).ToString();
                    imageInfoList[imgIndex].ImgNum = int.Parse(txt.Text);
                }
            }
        }

        private void sbtnAdd_Click(object sender, EventArgs e)
        {
            int index = Int32.Parse(((SkinButton)sender).Name.Replace("sbtnAdd", ""));
            Control control = Controls.Find("pictureBox" + (index).ToString(), true)[0];
            PictureBox pb = (PictureBox)control;
            if (pb.Image != null)
            {
                int imgIndex = (currpage - 1) * 8 + index - 1;
                control = Controls.Find("txtNum" + index.ToString(), true)[0];
                TextBox txt = (TextBox)control;
                if (txt.Text == "")
                    txt.Text = "1";
                tempNum = Convert.ToInt32(txt.Text);
                txt.Text = (int.Parse(txt.Text) + 1).ToString();
                imageInfoList[imgIndex].ImgNum = int.Parse(txt.Text);
                //surplusnum--;
                //totalnum++;
                //ReplaceMessage();
            }
        }

        private void txtNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                int kc = (int)e.KeyChar;
                if ((kc < 48 || kc > 57) && kc != 8)
                    e.Handled = true;

            }
            catch (Exception)
            {
            }
        }

        /// <summary>
        /// 留白事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtnLiubai_Click(object sender, EventArgs e)
        {
            int strIndex = Int32.Parse(((SkinButton)sender).Name.Replace("sbtnLiubai", "")) - 1;
            Control control = Controls.Find("pictureBox" + (strIndex + 1).ToString(), true)[0];
            PictureBox pb = (PictureBox)control;
            if (pb.Image != null)
            {
                int imgIndex = (currpage - 1) * 8 + strIndex;
                imageInfoList[imgIndex].IsCut = false;
                pb.Invalidate();
            }
        }

        /// <summary>
        /// 裁剪事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtnCut_Click(object sender, EventArgs e)
        {
            int strIndex = Int32.Parse(((SkinButton)sender).Name.Replace("sbtnCut", "")) - 1;
            Control control = Controls.Find("pictureBox" + (strIndex + 1).ToString(), true)[0];
            PictureBox pb = (PictureBox)control;
            if (pb.Image != null)
            {
                int imgIndex = (currpage - 1) * 8 + strIndex;
                //iscutList[imgIndex] = true;
                imageInfoList[imgIndex].IsCut = true;
                pb.Invalidate();
            }
        }

        /// <summary>
        /// 批量留白
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sbtnBatchmap_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < imageInfoList.Count; i++)
            {
                if (imageInfoList[i] != null)
                    imageInfoList[i].IsCut = false;
            }
            LoadAllControl(this.Controls);
        }

        private void LoadAllControl(Control.ControlCollection ctls)
        {
            foreach (Control c in ctls)
            {
                string name = c.Name;
                if (c.Controls.Count > 0)
                {
                    LoadAllControl(c.Controls);
                }
                if (c.GetType() == typeof(PictureBox)) //按类型查找
                {
                    if (c != null)
                        c.Invalidate();
                }
            }
        }

        private void sbtnDel_Click(object sender, EventArgs e)
        {
            int strIndex = Int32.Parse(((SkinButton)sender).Name.Replace("sbtnDel", "")) - 1;
            Control control = Controls.Find("pictureBox" + (strIndex + 1).ToString(), true)[0];
            PictureBox pb = (PictureBox)control;
            if (pb.Image != null)
            {
                int picIndex = (currpage - 1) * 8 + strIndex;
                imageInfoList[picIndex] = new ImageInfo() { Img = null, ImgPath = "", IsOpenPic = true };
                pb.Image = null;
                control = Controls.Find("sbtnOpenpic" + (strIndex + 1).ToString(), true)[0];
                SkinButton sbtn = (SkinButton)control;
                sbtn.Visible = true;
                //surplusnum++;
                //totalnum--;
                sizeImageInfo.totalnum--;
                sizeImageInfo.surplusnum++;
                completedpic--;
                ReplaceMessage();
                //label8.Text = "当前总共已处理" + string.Format("{0}", completedpic) + "张图片";
                label2.Text = completedpic.ToString();
            }
        }

        private void sbtnOpenpic_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = "image files (*.jpg)|*.jpg|image files (*.jpeg)|*.jpeg|image files (*.png)|*.png|All files (*.*)|*.*";
            this.openFileDialog1.Multiselect = false;
            this.openFileDialog1.FileName = "请选择文件";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string FileNames = openFileDialog1.FileName;
                int strIndex = Int32.Parse(((SkinButton)sender).Name.Replace("sbtnOpenpic", "")) - 1;
                Control control = Controls.Find("pictureBox" + (strIndex + 1).ToString(), true)[0];
                PictureBox pb = (PictureBox)control;

                int picIndex = (currpage - 1) * 8 + strIndex;

                Image image = Image.FromFile(FileNames);
                ImageInfo imageInfo = new ImageInfo();
                imageInfo.IsCut = true;
                imageInfo.CanMove = false;

                AdjustmentImgRotation(image, psi.height, psi.width, imageInfo);
                //imageInfo.Img = CreateBigPic(image);
                //imageInfo.Img = image;
                imageInfo.ImgPath = FileNames;
                imageInfoList[picIndex] = imageInfo;
                pb.Image = image;

                //surplusnum--;
                //totalnum++;
                sizeImageInfo.totalnum++;
                sizeImageInfo.surplusnum--;
                completedpic++;
                ReplaceMessage();
                label2.Text = completedpic.ToString();

                ((SkinButton)sender).Visible = false;
            }
        }

        private void txtNum_KeyUp(object sender, KeyEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            int index = Int32.Parse(((TextBox)sender).Name.Replace("txtNum", ""));
            if (txt.Text == "0" || txt.Text == "" || txt.Text == "01")
            {
                txt.Text = "1";
                int imgIndex = (currpage - 1) * 8 + index - 1;
                imageInfoList[imgIndex].ImgNum = 1;
            }
        }

        private void txtNum_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (isTxtChange)
                {
                    TextBox txt = (TextBox)sender;
                    int strIndex = Int32.Parse(((TextBox)sender).Name.Replace("txtNum", "")) - 1;
                    Control control = Controls.Find("pictureBox" + (strIndex + 1).ToString(), true)[0];
                    PictureBox pb = (PictureBox)control;
                    if (pb.Image != null)
                    {
                        int num = Convert.ToInt32(txt.Text);
                        int imgIndex = (currpage - 1) * 8 + strIndex;
                        sizeImageInfo.totalnum = sizeImageInfo.totalnum - tempNum + num;
                        sizeImageInfo.surplusnum = sizeImageInfo.surplusnum + tempNum - num;
                        tempNum = num;
                        imageInfoList[imgIndex].ImgNum = tempNum;
                        ReplaceMessage();
                    }
                    else
                    {
                        txt.Text = "1";
                    }
                }
            }
            catch { }
        }

        private void txtNum_MouseDown(object sender, MouseEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            tempNum = Convert.ToInt32(txt.Text);
        }

        private void llbLog_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (sizeImageInfo.iserror)
            {
                System.Diagnostics.Process.Start("notepad.exe", Application.StartupPath + @"\Log\" + sizeImageInfo.errorfile + ".txt");
            }
        }

    }
}
